package com.g2room.myuall.grap.univ;

import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.g2room.myuall.grap.univ.po.MajecScorePo;
import com.g2room.myuall.grap.univ.to.AdminScoreTo;
import com.g2room.myuall.util.DbUtil;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.qiniu.util.Json;

public class GrapEolMajocScore implements Runnable {
	static String baseUrl = "http://gkcx.eol.cn";
	// 抓取各个专业
	static String pageUrl = "http://data.api.gkcx.eol.cn/soudaxue/queryspecialty.html?messtype=json&zycengci=&zytype=&keyWord2=&schoolsort=&callback=j&_=1470740285738&size=50&page="; 
//	static Map<String, Boolean> grapedUrls = getGrapedUrl();
	
	static List<String> errList = new ArrayList<String>();
	static {}
	
	public static void main(String[] args) {
		for(int i =0; i<30; i++) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			GrapEolMajocScore gue = new GrapEolMajocScore();
			Thread t = new Thread(gue);
			t.start();
		}
		
//		for(String url : errList) {
//			Boolean r = grapedUrls.get(url);
//			if(null != r && r) {
//				continue;
//			}
//			System.out.println(url);
//			gue.getList(url);
//		}
	}

	@Override
	public void run() {
		List<String> listUrls = getUrl();
		if(null == listUrls) return;
		for(String url : listUrls) {
			getList(url);
		}
	}
	
	public static AtomicInteger page = new AtomicInteger(1);
	private static synchronized List<String> getUrl() {
		int l = 5;
		int max = 26;
		if(page.intValue() > max) return null;
		List<String> listUrls = new ArrayList<String>();
		for(int i = page.intValue(); i< page.intValue() + l; i++) {
			if(i>max) break;
//			Boolean r = grapedUrls.get(pageUrl+i);
//			if(null != r && r) {
//				continue;
//			}
			listUrls.add(pageUrl+i);
		}
		page.addAndGet(l);
		return listUrls;
	}
	
	/**
	 * 获取分页列表数据
	 * @param url
	 * @throws FailingHttpStatusCodeException
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public void getList(String url) {
		String body = null;
		try {
			body = new GenericMyuall().getJsonContent(url);
		} catch (Exception e1) {
			e1.printStackTrace();
			insert2ErrDb(url, 1);
			return;
		}
		if(null == body) return;
		try {
			body = body.replaceAll("\\[\\]", "\"\"");
			AdminScoreTo adminScoreTo = Json.decode(body, AdminScoreTo.class);
//			for(MajecScorePo as : adminScoreTo.getSchool()) {
//				getDetail(baseUrl + as.getSpecialurl(), as);
//			}
		} catch (Exception e1) {
			e1.printStackTrace();
			insert2ErrDb(url, 2);
			return;
		}
	}
	
	/**
	 * 获取分页列表数据
	 * @param url
	 * @throws FailingHttpStatusCodeException
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public void getDetail(String url, MajecScorePo ms) {
		Document doc = null;
		try {
			doc = new GenericMyuall().getDoc(url);
		} catch (Exception e1) {
			e1.printStackTrace();
			insert2ErrDb(url, 10);
			return;
		}
		if(null == doc) return;
		try {
			Element pel = doc.getElementsByAttributeValue("class", "query_box S_result_kx mar_t_20").first();
			ms.setDetail(pel.html());
			insert2Db(ms);
			insert2GrapedDb(url);
		} catch (Exception e1) {
			e1.printStackTrace();
			insert2ErrDb(url, 11);
			return;
		}
	}
	
	public void insert2Db(MajecScorePo as) {
		try {
			PreparedStatement univPs = DbUtil.getConn().prepareStatement("INSERT INTO `major` ("
					+ "specialname,code,specialurl,zycengci,zytype,bnum,znum,zyid,ranking,rankingType,detail) "
					+ "values(?,?,?,?,?,?,?,?,?,?,?)");
			
			univPs.setString(1, as.getSpecialname());
			univPs.setString(2, as.getCode());
			univPs.setString(3, as.getSpecialurl());
			univPs.setString(4, as.getZycengci());
			univPs.setString(5, as.getZytype());
			univPs.setString(6, as.getBnum());
			univPs.setString(7, as.getZnum());
			univPs.setString(8, as.getZyid());
			univPs.setString(9, as.getRanking());
			univPs.setString(10, as.getRankingType());
			univPs.setString(11, as.getDetail());
			univPs.execute();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void insert2ErrDb(String url, int type) {
		try {
			PreparedStatement errPs = DbUtil.getConn().prepareStatement("INSERT INTO `univ_err` (`url`, `type`) "
					+ "values(?,?)");
			errPs.setString(1, url);
			errPs.setInt(2, type);
			errPs.execute();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void insert2GrapedDb(String url) {
		try {
			PreparedStatement grapPs = DbUtil.getConn().prepareStatement("INSERT INTO `univ_graped` (`url`) "
					+ "values(?)");
			grapPs.setString(1, url);
			grapPs.execute();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Map<String, Boolean> getGrapedUrl() {
		Map<String, Boolean> its = new HashMap<String, Boolean>();
		try {
			Connection connection = DbUtil.getConn();
			Statement statement = connection.createStatement();
			String sql = "select url from univ_graped";
			ResultSet rs = statement.executeQuery(sql);
			while(rs.next()) {
				its.put(rs.getString("url"), true);
			}
			rs.close();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
		return its;
	}

}